<template>
  <div
    id="floating-button"
    :style="{
      left: `${positionX}px`,
      top: `${positionY}px`,
      transition: isDragging ? 'none' : transitionStyle,
    }"
    @mousedown="startDrag"
    @touchstart="startDrag"
    @mouseup="handleMouseUp"
    @touchend="handleMouseUp"
  >
    <slot>悬浮按钮</slot>
  </div>
</template>

<script>
export default {
  name: "FloatingButton",
  data() {
    return {
      positionX: window.innerWidth - 80,
      positionY: window.innerHeight / 2 - 40,
      startX: 0,
      startY: 0,
      originX: 0,
      originY: 0,
      isDragging: false,
      buttonWidth: 60,
      buttonHeight: 60,
      margin: 10,
      transitionStyle: "left 0.3s ease, top 0.3s ease",
      moveHandler: null,
      endHandler: null,
      animationFrameId: null,
      clickThreshold: 5 // 点击阈值，可根据实际情况调整
    };
  },
  mounted() {
    window.addEventListener("resize", this.handleResize);
    this.handleResize();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    this.removeGlobalListeners();
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
  },
  methods: {
    handleResize() {
      this.positionX = Math.max(
        this.margin,
        Math.min(
          this.positionX,
          window.innerWidth - this.buttonWidth - this.margin
        )
      );
      this.positionY = Math.max(
        this.margin,
        Math.min(
          this.positionY,
          window.innerHeight - this.buttonHeight - this.margin
        )
      );
    },
    startDrag(e) {
      e.preventDefault();
      e.stopPropagation();

      this.isDragging = false;
      this.transitionStyle = "none";

      const point = e.type === 'mousedown' ? e : e.touches[0];
      this.startX = point.clientX;
      this.startY = point.clientY;
      this.originX = point.clientX;
      this.originY = point.clientY;

      // 添加全局事件监听器
      this.moveHandler = this.throttle(this.onDrag, 10);
      this.endHandler = this.handleMouseUp;

      window.addEventListener("mousemove", this.moveHandler);
      window.addEventListener("mouseup", this.endHandler);
      window.addEventListener("touchmove", this.moveHandler);
      window.addEventListener("touchend", this.endHandler);
    },
    onDrag(e) {
      e.preventDefault();
      e.stopPropagation();

      const point = e.type === 'mousemove' ? e : e.touches[0];
      const totalDeltaX = Math.abs(point.clientX - this.originX);
      const totalDeltaY = Math.abs(point.clientY - this.originY);

      // 判断是否超过点击阈值
      if (totalDeltaX > this.clickThreshold || totalDeltaY > this.clickThreshold) {
        this.isDragging = true;
      }

      if (!this.isDragging) return;

      let clientX = point.clientX;
      let clientY = point.clientY;

      // 使用requestAnimationFrame优化渲染性能
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }

      this.animationFrameId = requestAnimationFrame(() => {
        const deltaX = clientX - this.startX;
        const deltaY = clientY - this.startY;

        this.positionX += deltaX;
        this.positionY += deltaY;

        this.positionX = Math.max(
          this.margin,
          Math.min(
            this.positionX,
            window.innerWidth - this.buttonWidth - this.margin
          )
        );
        this.positionY = Math.max(
          this.margin,
          Math.min(
            this.positionY,
            window.innerHeight - this.buttonHeight - this.margin
          )
        );

        this.startX = clientX;
        this.startY = clientY;
      });
    },
    handleMouseUp(e) {
      const point = e.type === 'mouseup' ? e : e.changedTouches[0];
      const totalDeltaX = Math.abs(point.clientX - this.originX);
      const totalDeltaY = Math.abs(point.clientY - this.originY);

      if (!this.isDragging && totalDeltaX <= this.clickThreshold && totalDeltaY <= this.clickThreshold) {
        console.log('悬浮按钮被点击了');
        // 这里可以添加你需要执行的点击逻辑
        this.$emit('click');
      }

      this.isDragging = false;
      this.transitionStyle = "left 0.3s ease, top 0.3s ease";

      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }

      const middleX = window.innerWidth / 2;
      if (this.positionX < middleX) {
        this.positionX = this.margin;
      } else {
        this.positionX = window.innerWidth - this.buttonWidth - this.margin;
      }

      this.removeGlobalListeners();
    },
    removeGlobalListeners() {
      if (this.moveHandler) {
        window.removeEventListener("mousemove", this.moveHandler);
        window.removeEventListener("touchmove", this.moveHandler);
        this.moveHandler = null;
      }

      if (this.endHandler) {
        window.removeEventListener("mouseup", this.endHandler);
        window.removeEventListener("touchend", this.endHandler);
        this.endHandler = null;
      }
    },
    // 节流函数，限制函数调用频率
    throttle(fn, delay) {
      let lastCall = 0;
      return function (...args) {
        const now = new Date().getTime();
        if (now - lastCall < delay) {
          return;
        }
        lastCall = now;
        return fn.apply(this, args);
      };
    }
  },
};
</script>

<style scoped>
#floating-button {
  position: fixed;
  z-index: 9999;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  user-select: none;
  -webkit-user-select: none;
  touch-action: none;
}
</style>